//
//  SearchViewController.m
//  WuLi
//
//  Created by Gollum on 16/9/13.
//  Copyright © 2016年 Gollum. All rights reserved.
//

#import "SearchViewController.h"
#import "NetworkTool.h"
#import "SearchModel.h"
#import "SearchSectionModel.h"
#import "SearchCollectionViewCell.h"
#import "SeachCollectionReusableView.h"
#import "SeachCollectionViewLayOut.h"
#import "JHDBHandle.h"


#import "RootSeachModel.h"
#import "RootSearchAttached.h"
#import "RootSearchData.h"
#import "RootSearchNewsimageinfolist.h"
#import "RootSearchNewssummaryinfolist.h"
#import "RootSearchParamap.h"
#import "RootSearchScene_Current.h"
#import "RootSearchScenesummaryinfo.h"

static NSString *const cxSearchCollectionViewCell = @"CXSearchCollectionViewCell";

static NSString *const headerViewIden = @"HeadViewIden";

@interface SearchViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,SelectCollectionCellDelegate,UICollectionReusableViewButtonDelegate>

@property (weak, nonatomic) IBOutlet UITextField *searchTextField;

@property (weak, nonatomic) IBOutlet UICollectionView *searchCollectionView;


/**
 *  存储网络请求的热搜，与本地缓存的历史搜索model数组
 */
@property (nonatomic, strong) NSMutableArray *sectionArray;
/**
 *  存搜索的数组 字典
 */
@property (nonatomic,strong) NSMutableArray *searchArray;

@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)RootSeachModel *searchModel;

@end

@implementation SearchViewController

-(NSMutableArray *)sectionArray
{
    if (_sectionArray == nil) {
        _sectionArray = [NSMutableArray array];
    }
    return _sectionArray;
}

-(NSMutableArray *)searchArray
{
    if (_searchArray == nil) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}





- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    
//    [self handleData];
    
    
    [self prepareData];
    
    [self.searchCollectionView setCollectionViewLayout:[[SeachCollectionViewLayOut alloc] init] animated:YES];
    [self.searchCollectionView registerClass:[SeachCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIden];
    [self.searchCollectionView registerNib:[UINib nibWithNibName:@"SearchCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cxSearchCollectionViewCell];
    /***  可以做实时搜索*/
        [self.searchTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];

}
- (void)textFieldChange:(NSString *)text{

//    [self handleData];
//    [self handleSearch];
    
}



- (void)prepareData
{
    /**
     *  测试数据 ，字段暂时 只用一个 titleString，后续可以根据需求 相应加入新的字段
     */
    NSDictionary *testDict = @{@"section_id":@"1",@"section_title":@"热搜",@"section_content":@[@{@"content_name":@"军事迷"},@{@"content_name":@"段子手"},@{@"content_name":@"涨知识"},@{@"content_name":@"笑点低"},@{@"content_name":@"发现"},@{@"content_name":@"二次元"},@{@"content_name":@"电影范"},@{@"content_name":@"动物园"},@{@"content_name":@"星座控"},@{@"content_name":@"社会摇"},@{@"content_name":@"爱搞机"},@{@"content_name":@"八卦震"},@{@"content_name":@"体育圈"}]};
    NSMutableArray *testArray = [@[] mutableCopy];
    [testArray addObject:testDict];
    
    /***  去数据查看 是否有数据*/
    NSDictionary *parmDict  = @{@"category":@"1"};
    NSDictionary *dbDictionary =  [JHDBHandle statusesWithParams:parmDict];
    
    if (dbDictionary.count) {
        
        [testArray addObject:dbDictionary];
        [self.searchArray addObjectsFromArray:dbDictionary[@"section_content"]];
    }
    
    for (NSDictionary *sectionDict in testArray) {
        SearchSectionModel *model = [[SearchSectionModel alloc]initWithDictionary:sectionDict];
        [self.sectionArray addObject:model];
    }
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.searchTextField becomeFirstResponder];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    SearchSectionModel *sectionModel =  self.sectionArray[section];
    return sectionModel.section_contentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cxSearchCollectionViewCell forIndexPath:indexPath];
    SearchSectionModel *sectionModel =  self.sectionArray[indexPath.section];
    SearchModel *contentModel = sectionModel.section_contentArray[indexPath.row];
    [cell.contentButton setTitle:contentModel.content_name forState:UIControlStateNormal];
    cell.slectDelegate = self;
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.sectionArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    if ([kind isEqualToString: UICollectionElementKindSectionHeader]){
        SeachCollectionReusableView* view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIden forIndexPath:indexPath];
        view.delectDelegate = self;
        SearchSectionModel *sectionModel =  self.sectionArray[indexPath.section];
        [view setText:sectionModel.section_title];
        /***  此处完全 也可以自定义自己想要的模型对应放入*/
        if(indexPath.section == 0)
        {
            [view setImage:@"cxCool"];
            view.delectButton.hidden = YES;
        }else{
            [view setImage:@"cxSearch"];
            view.delectButton.hidden = NO;
        }
        reusableview = view;
    }
    return reusableview;
}

- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchSectionModel *sectionModel =  self.sectionArray[indexPath.section];
    if (sectionModel.section_contentArray.count > 0) {
        SearchModel *contentModel = sectionModel.section_contentArray[indexPath.row];
        return [SearchCollectionViewCell getSizeWithText:contentModel.content_name];
    }
    return CGSizeMake(80, 24);
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
}

#pragma mark - SelectCollectionCellDelegate
- (void)selectButttonClick:(SearchCollectionViewCell *)cell;
{
    NSIndexPath* indexPath = [self.searchCollectionView indexPathForCell:cell];
    SearchSectionModel *sectionModel =  self.sectionArray[indexPath.section];
    SearchModel *contentModel = sectionModel.section_contentArray[indexPath.row];
    NSLog(@"您选的内容是：%@",contentModel.content_name);
    
    UIAlertView *al = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"您该去搜索 %@ 的相关内容了",contentModel.content_name] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"知道了！", nil];
    [al show];
}

#pragma mark - UICollectionReusableViewButtonDelegate
- (void)delectData:(SeachCollectionReusableView *)view;
{
    if (self.sectionArray.count > 1) {
        [self.sectionArray removeLastObject];
        [self.searchArray removeAllObjects];
        [self.searchCollectionView reloadData];
        [JHDBHandle saveStatuses:@{} andParam:@{@"category":@"1"}];
    }
}
#pragma mark - scrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.searchTextField resignFirstResponder];
}
#pragma mark - textField
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([[textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]){
        return NO;
    }
    /***  每搜索一次   就会存放一次到历史记录，但不存重复的*/
    if ([self.searchArray containsObject:[NSDictionary dictionaryWithObject:textField.text forKey:@"content_name"]]) {
        return YES;
    }
    [self reloadData:textField.text];
    return YES;
}
- (void)reloadData:(NSString *)textString
{
    [self.searchArray addObject:[NSDictionary dictionaryWithObject:textString forKey:@"content_name"]];
    
    NSDictionary *searchDict = @{@"section_id":@"2",@"section_title":@"历史记录",@"section_content":self.searchArray};
    
    /***由于数据量并不大 这样每次存入再删除没问题  存数据库*/
    NSDictionary *parmDict  = @{@"category":@"1"};
    [JHDBHandle saveStatuses:searchDict andParam:parmDict];
    
    SearchSectionModel *model = [[SearchSectionModel alloc]initWithDictionary:searchDict];
    if (self.sectionArray.count > 1) {
        [self.sectionArray removeLastObject];
    }
    [self.sectionArray addObject:model];
    [self.searchCollectionView reloadData];
    self.searchTextField.text = @"";
    
    
}

- (IBAction)cancleButton:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


//- (void)handleData{
//    
//    
//    NSString *urlString = @"http://211.151.51.80/v1/message/search";
//    
//    NSDictionary *body = @{@"key":_searchTextField.text, @"from":@"0", @"size":@"10"};
//    NSDictionary *header = @{@"User-Agent":@"Dalvik/2.1.0 (Linux; U; Android 5.0; ASUS_Z00ADB Build/LRX21V) Wuli/2.4.0 (agent:s;channel:pphl;credential:e1MyMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzM1Nzg3MjA2MTcxNDM4M30teyMjIyMjIyMxNDcyMDAyMTMyOTYzLTJlZjRjNThjZDJ9QDE0NzI0ODIyNDIyNzc=;deviceId:357872061714383;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:5.0;idfa:null)", @"Host":@"api.5wuli.com", @"Content-Type":@"application/json;charset=utf-8"};
//    
//    [NetworkTool POST:urlString andBody:body andBodyStyle:JHBodyJSON andHeader:header andResponse:JHJSON andSuccessBlock:^(id result) {
//        
//        NSLog(@"======================%@",result);
//    } andFailureBlock:^(NSError *error) {
//        
//    }];
//    
//    }


- (void)handleSearch{
    
    
    NSString *urlString = @"http://api.5wuli.com/v1/message/search";
    
    NSDictionary *header = @{@"User-Agent":@"Dalvik/2.1.0 (Linux; U; Android 5.0; ASUS_Z00ADB Build/LRX21V) Wuli/2.4.0 (agent:s;channel:pphl;credential:e1MyMDEwMDAxMDF9LXsjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIzM1Nzg3MjA2MTcxNDM4M30teyMjIyMjIyMxNDcyMDAyMTMyOTYzLTJlZjRjNThjZDJ9QDE0NzM2MDAzMTAyODM=;deviceId:357872061714383;osTypeId:01;detailInfo:android;simTypeId:01;netTypeId:01;deviceTypeId:01;osVersion:5.0;idfa:null)", @"Host":@"api.5wuli.com",@"Content-Type":@"application/json;charset=UTF-8"};
    
    //    NSString *str1 = @"{\"key\": \"";
    //    NSString *str2 = @"\",\"from\": \"";
    //    NSString *str3 = @"\",\"size\": \"";
    //    NSString *str4 = @"\"}";
    //    int i = 0;
    //    NSString *num = [NSString stringWithFormat:@"%d",i++];
    //    NSString *bodyString = [[[[[[str1 stringByAppendingString:@"军事"] stringByAppendingString:str2] stringByAppendingString:num]
    //                              stringByAppendingString:str3] stringByAppendingString:@"10"] stringByAppendingString:str4];
    //    NSLog(@"%@",num);
    NSString *str = @"\"key\":\"";
    NSString *str2 = @"\",\"from\":\"0\",\"size\":\"10\"}";
    NSString *bodyString = [[str stringByAppendingString:_searchTextField.text] stringByAppendingString:str2];
    
//    NSString *bodyString = @"{\"key\":\"军事\",\"from\":\"0\",\"size\":\"10\"}";
    
    [NetworkTool POST:urlString andBody:bodyString andBodyStyle:JHBodyString andHeader:header andResponse:JHJSON andSuccessBlock:^(id result) {
        
        //        NSLog(@"------------------++++++++++++%@",result);
        //        _rankModel = [RankModel modelWithDic:result];
        //        _recommend = [RecommendModel modelWithDic:result];
        
        _searchModel = [RootSeachModel modelWithDic:result];
        
        [_dataArray addObject:_searchModel];
        
        NSString *srcLink = _searchModel.data[0].newsSummaryInfoList[0].srcLink;
        NSLog(@"$$$$$$$$$$$$$$$$$$%@",srcLink);
        [NetworkTool GET:srcLink andBody:nil andHeader:header andResponse:JHJSON andSuccessBlock:^(id result) {
            NSLog(@"============================================================================================%@",result);
            NSArray *arr =[result objectForKey:@"documents"];
            NSDictionary *dic = arr[0];
            NSString *url = [dic objectForKey:@"url"];
            NSLog(@"-=--=-=-=-=%@",url);
            UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
            [self.view addSubview:webView];
            
            NSURL *urlstr  = [NSURL URLWithString:url];
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:urlstr];
            [webView loadRequest:request];
            
        } andFailureBlock:^(NSError *error) {
            
        }];
        
        
    } andFailureBlock:^(NSError *error) {
        
        NSLog(@"请求失败");
        
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
